package com.cnswhy.cloud.server.comsumer.consumer;

import com.cnswhy.cloud.server.common.entity.enumeration.*;
import com.cnswhy.cloud.server.common.entity.mq.SplitAccountMQ;
import com.cnswhy.cloud.server.comsumer.event.SplitAccountEvent;
import com.cnswhy.cloud.server.core.entity.SplitTransRecord;
import com.cnswhy.cloud.server.core.service.SplitTransRecordService;
import com.cnswhy.cloud.server.core.wallet.WalletService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SplitAccountConsumer implements SplitAccountEvent {
    @Autowired
    SplitTransRecordService splitTransRecordService;
    @Autowired
    WalletService walletService;
    @Override
    public void splitInAccount(SplitAccountMQ splitAccountMQ) {
        if(splitAccountMQ.getSplitTransRecordId() == null){
            log.error("split_trans_record_id is null");
            return;
        }
        SplitTransRecord splitTransRecord = splitTransRecordService.getById(splitAccountMQ.getSplitTransRecordId());
        if(splitTransRecord == null){
            log.error("split_trans_record not found :{} id", splitAccountMQ.getSplitTransRecordId());
            return;
        }
        if(AccountFlag.FINISNED.getVal() == splitTransRecord.getAccountFlag()){
            //分账完成
            log.info("split_trans_record id = {} account finished!", splitTransRecord.getId());
            return;
        }
        if(BusType.CPS_NO_CARD.eq(splitTransRecord.getBusType())){
            walletService.checkAndCreate(splitTransRecord.getSplitCustomerId(),WalletType.BALANCE,0L);
            walletService.add(splitTransRecord.getSplitCustomerId(), WalletType.BALANCE, TransType.NO_CARD_SPLIT,splitTransRecord.getSplitAmt(),splitTransRecord.getOrderId());
        }else if(BusType.IOT_CHARG_LINE.eq(splitTransRecord.getBusType())){
            walletService.checkAndCreate(splitTransRecord.getSplitCustomerId(),WalletType.BALANCE,0L);
            walletService.add(splitTransRecord.getSplitCustomerId(), WalletType.BALANCE, TransType.IOTCL_SPLIT,splitTransRecord.getSplitAmt(),splitTransRecord.getOrderId());
        }

        splitTransRecord.setAccountFlag(AccountFlag.FINISNED.getVal());
        splitTransRecordService.updateById(splitTransRecord);

    }
}
